﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Data;
using System.Data.SqlClient;

public partial class SearchResults : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session.IsNewSession)
        {
            // If it says it is a new session, but an existing cookie exists, then it must 
            // have timed out (can't use the cookie collection because even on first 
            // request it already contains the cookie (request and response
            // seem to share the collection)
            string szCookieHeader = Request.Headers["Cookie"];
            if ((null != szCookieHeader) && (szCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
            {
                Response.Redirect("sessionTimeout.aspx");
            }
        }

        string s = this.Request.QueryString["string"].ToString();
        if (this.Application["allproducts"] != null)
        {
            //Seek for the search string in the products names stored in memory
            ArrayList allproducts = this.Application["allproducts"] as ArrayList;
            bool noresults = true;
            foreach (qman.DataHelp.couple_Product_Company productCouple in allproducts)
            {
                string productName = productCouple.product.Root.name;
                string companyUsername = productCouple.company_username;
                if (productName.ToLower() == s.ToLower()
                    || productName.ToLower().Contains(" " + s.ToLower()) 
                    || productName.ToLower().Contains(" " + s.ToLower() + " ")
                    || productName.ToLower().Contains(s.ToLower() + " "))

                {
                    //Get the company name for that product from the database
                    DataSet ds = qman.DataHelp.DataAccess.getDataSet("select company_name from company_accounts where [user]='" + companyUsername + "'");
                    string companyName = ds.Tables[0].Rows[0][0].ToString();

                    //Add new item to the bulleted list
                    ListItem item = new ListItem();
                    item.Text = "\"" + productName + "\"" + " by " + companyName;
                    item.Value = "~/Private/TreeView.aspx?cun=" + companyUsername + "&product=" + productName;
                    this.BulletedList1.Items.Add(item);
                    if (noresults) noresults = false; 
                }
            }

            if (noresults) 
            {
                ListItem item = new ListItem();
                item.Text = "No results found.";
                item.Value = "";
                this.BulletedList1.Items.Add(item);
            }
        }
    }
}
